<script lang="ts" setup>
import { useVbenDrawer,useVbenModal } from '@vben/common-ui';
import type { DataType } from './types';
import { Button, message, Popconfirm, Space ,Image,Modal} from 'ant-design-vue';
import Draggable from 'vuedraggable';
import { $t } from '@vben/locales';
import type { VxeGridListeners, VxeGridProps} from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deletePage_news, getPage_news ,update_sort,deleteMultiple} from '#/api/portal/vechiledetail';
import Icon from '#/components/Icons';
import { formatImagesList, queryStringToObject} from '#/utils';
import { getPage_news as car_model } from '#/api/portal/carmodel';
import {FeaturesModal as FeaturesModalView} from "../../components"

const categoriesTree = ref([]);
const route = useRoute();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const code = ref('');
const carOptions = ref([]); // ✅ 外部定义，响应式
const id= ref(0);

const modalVisible = ref(false); // 控制 Modal 显示
const gridOptions: VxeGridProps<DataType> = {
   checkboxConfig:{
    range: true, // 可选：支持 shift 连选
  },
  rowConfig: {
    isCurrent: true,
    isHover: true,
     drag: true,
  },
  pagerConfig: {
    enabled: false,
  },
  columns: [
    // { field: 'carModel.category.name', title: '类型' },
    // { field: 'carModel.name', title: '车型' },
    { field: 'name', title: $t('page.common.Features') , dragSort: true},
    { field: 'images', title: $t('page.common.Image'),slots:{default:'image'} },

    {
        slots: { default: 'action' },
        field: 'action',
        fixed: 'right',
        title: $t('page.common.Action'),
        width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,

  // proxyConfig: {
  //   ajax: {
  //     query: async ({ page }, formValues) => {
  //       const { data } = await getPage_news({car_model:id.value!=0?id.value:-1 });
  //       const total = data.list.length;
      
  //       data.list = formatImagesList(data.list, 'images');
  //       return data;
  //     },
  //   },
  // },
  toolbarConfig: {
    custom: false,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,

});
const gridEvents: VxeGridListeners<AddDataType> = {
  async rowDragend() {
    const visibleData = GridApi.grid.getTableData().visibleData;
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    visibleData.forEach((item, index) => {
      result[item.id] = index;
    });

  await update_sort({ list_orders: result });
  },
};
const handleDelete = async (row: DataType) => {
    const $table = GridApi.grid;
    $table.remove(row);
  };



const [Drawer, DrawerApi] = useVbenDrawer({
    async onConfirm() {
            const $table = GridApi.grid;
            DrawerApi.setData($table.getTableData())
            DrawerApi.close();
    },
    async onOpenChange(isOpen) {
        if (isOpen) {
        const modalData: any = await DrawerApi.getData();
        id.value = modalData.id;
        const datas = modalData.vechiledetal;

        if(datas){ 
        
              GridApi.setGridOptions({
                    border: true,
                    data: datas,
                    keepSource: true,
                    scrollX: {
                      enabled: true,
                    },
                    rowConfig:{
                      height:60
                    },
                    pagerConfig: {
                      enabled: false,
                    },
                 
              });
             
        }
        }
    }
})





const [AttributesModal, AttributesModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FeaturesModalView,
  onClosed() {
    const $table = GridApi.grid;
    const datas =AttributesModalApi.getData();

    if(datas._X_ROW_KEY){
                const index = $table.getTableData().tableData.findIndex(item => {
                const isTarget = item._X_ROW_KEY === datas._X_ROW_KEY;
                if (isTarget) $table.remove(item); // 找到目标就删除
                return isTarget;
                });

                if (index !== -1) {
                    if($table.getTableData().tableData.length>0 ){
                      if(index==$table.getTableData().tableData.length){
                          $table.insertNextAt(datas,-1); 
                      }else{
                          $table.insertAt(datas, index); 
                      }

                    }else{
                        $table.insertNextAt(datas,-1); 
                    }

                } else {
                      $table.insertNextAt(datas,-1); 
                }

          }else{
              if(datas.isUpdata){
                  $table.insertNextAt(datas,-1); 
          }
               
  }
    
  },
});
const handleExtra = (row) => {
  AttributesModalApi.setState({
    title: `编辑数据`,
  });
  console.log(row);
if(row==null)row={car_model:id.value}

 AttributesModalApi.setData({ row: row });

  AttributesModalApi.open();
};  
</script>
<template>
    <Drawer>
          <Page auto-content-height>
                    <Grid :grid-events="gridEvents" :table-title="$t('page.common.List')">
                    
                    <template #image="{ row }">
                        <Image
                        v-if="Array.isArray(row.images) && row.images.length > 0 && row.images[0].url"
                        :src="row.images[0].url"
                        :height="30"
                        :width="30"
                        />
                    </template>
                    <template #toolbar-tools>
                        <Modal v-model:visible="modalVisible" title="确认删除" class="w-[600px]">
                            <template #default>
                            <p>你确定要删除选中的 {{ selectedRows.length }} 项吗？此操作无法恢复。</p>
                            </template>
                            <template #footer>
                            <VbenButton @click="modalVisible = false">取消</VbenButton>
                            <VbenButton type="primary" danger @click="openDeleteConfirm()">确认删除</VbenButton>
                            </template>
                        </Modal>
                        <Button class="mr-2" type="primary" @click="handleExtra(null)">
                        <span class="anticon">
                            <Icon icon="ri:add-line" />
                        </span>
                        {{$t('page.common.Add')}} banner
                        </Button>
                    </template>

                    <template #action="{ row }">
                        <Space>
                        <Button type="primary" @click="handleExtra(row)">
                            <template #icon>
                            <span class="anticon">
                                <Icon icon="ri:file-edit-line" />
                            </span>
                            </template>
                            {{$t('page.common.Edit')}}
                        </Button>
                        <Popconfirm
                            :cancel-text="$t('page.common.No')"
                            :ok-text="$t('page.common.yes')"
                            title="确认删除？"
                            @confirm="handleDelete(row)"
                        >
                            <Button danger type="primary">
                            <template #icon>
                                <span class="anticon">
                                <Icon icon="ri:delete-bin-line" />
                                </span>
                            </template>
                            {{$t('page.common.Delete')}}
                            </Button>
                        </Popconfirm>
                        </Space>
                    </template>
                    </Grid>
             </Page>
    </Drawer>
    <AttributesModal/>
</template>